/*
 * BearPlotterPanelView.java
 */

package panel;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


/**
 * The application's main frame.
 */
public class PlotterPanelView extends FrameView {

    private List<String> commands;
    private SerialPort serialPort;
    private List<CommPortIdentifier> ports;
    private InputStream recieveStream;
    private OutputStream sendStream;

    private BufferedReader recieveBuffer;

    public final int sizeX = 100;
    public final int sizeY = 200;

    private void loadPorts() {

        Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
        CommPortIdentifier portId = null;  // will be set if port found
        ports = new ArrayList<CommPortIdentifier>();

        while (portIdentifiers.hasMoreElements()) {

            CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
            ports.add(pid);
            if(pid.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                portComboBox.addItem(pid.getName());
            }
        }
    }

    private void openPort() {

        try {
            CommPortIdentifier identifier = ports.get(portComboBox.getSelectedIndex());
            serialPort = (SerialPort) identifier.open("Bear", 2000);

            sendStream = serialPort.getOutputStream();
            serialPort.setSerialPortParams(4800, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
            recieveStream = serialPort.getInputStream();
            recieveBuffer = new BufferedReader(new InputStreamReader(recieveStream));

        } catch (Exception exception) {
            JOptionPane.showMessageDialog(this.getComponent(),"The selected port could not be opened!",
                    "Serial Port Error", JOptionPane.ERROR_MESSAGE);
            exception.printStackTrace();
        }
    }

    private void processFile(File file) {

        commands = new ArrayList<String>();

        try {
            FileInputStream stream = new FileInputStream(file);
            InputStreamReader reader = new InputStreamReader(stream);
            BufferedReader buffer = new BufferedReader(reader);

            String text;
            while ( (text = buffer.readLine())!= null){

                String[] item = text.split(";");
                for (String string : item) {
                    commands.add(string);
                }
            }

        } catch (IOException ex) {
            Logger.getLogger(PlotterPanelView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void showCommands() {

        if(commands != null) {
            fileList.setListData(commands.toArray());
            fileList.setSelectedIndex(0);
        }
    }

    private void sendCommand(String command) {

        if (sendStream == null || recieveBuffer == null) {
            openPort();
        }

        try {
            sendStream.write(command.getBytes());
            sendStream.flush();
            String response = recieveBuffer.readLine();
            if(!(response.equals("DONE"))) {
                JOptionPane.showMessageDialog(this.getComponent(),"Error while procecing the command: " + command,
                    "Serial Port Error", JOptionPane.ERROR_MESSAGE);
            }

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this.getComponent(),"Communication error",
                    "Serial Port Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void getInfo() {


        try {
            String instruction = "GP" + '\0';
            sendStream.write(instruction.getBytes());
            sendStream.flush();

            int dimX = Integer.valueOf(recieveBuffer.readLine());
            int dimY = Integer.valueOf(recieveBuffer.readLine());
            int resolution = ((sizeX/dimX)+(sizeY/dimY))/2;

            xStepsField.setText(String.valueOf(dimX));
            yStepsField.setText(String.valueOf(dimY));

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this.getComponent(),"The parameters could not be read!",
                    "Application Error", JOptionPane.ERROR_MESSAGE);
        }


    }


    public PlotterPanelView(SingleFrameApplication app) {
        super(app);

        initComponents();
        loadPorts();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = PlotterPanelApp.getApplication().getMainFrame();
            aboutBox = new PlotterPanelAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        PlotterPanelApp.getApplication().show(aboutBox);
    }

    @Action
    public void openFileMenu() {

        JFileChooser window = new JFileChooser();
        int returnValue = window.showOpenDialog(this.getComponent());

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File file = window.getSelectedFile();
            processFile(file);
            showCommands();
        } else {
            JOptionPane.showMessageDialog(this.getComponent(), "Please select one file");
        }
    }

    @Action
    public void sendAllCommands() {

        if(commands != null && commands.size()>0) {
           for (String string : commands) {
               if (string.equals("IN") && (skipInitializationBox.isSelected() == true)) {
                   break;
               }
               sendCommand(string + ";" + '\0');
           }
        }
    }

    @Action
    public void sendNextCommand() {

        int item = fileList.getSelectedIndex();
        if (fileList.getModel().getSize() > 0) {
            String com = commands.get(item) + ";" + '\0';
            System.out.println(com);
            sendCommand(com);
            fileList.setSelectedIndex(item+1);
        } else {
            JOptionPane.showMessageDialog(this.getComponent(),"There isn't any command to send!",
                    "Aplication Error", JOptionPane.ERROR_MESSAGE);
        }

    }

    @Action
    public void disconect() {

        try {
            recieveBuffer.close();
            recieveStream.close();
            sendStream.close();
            serialPort.close();
            JOptionPane.showMessageDialog(this.getComponent(), "Connection close!");

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this.getComponent(),"Communication error",
                    "Serial Port Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    @Action
    public void getInfoButton() {

        if (sendStream == null || recieveBuffer == null) {
            openPort();
        }
        if(skipInitializationBox.isSelected() == false) {
            sendCommand("IN" + '\0');
        }
        getInfo();
    }



    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        filePanel = new javax.swing.JPanel();
        fileListLabel = new javax.swing.JLabel();
        fileListPanel = new javax.swing.JScrollPane();
        fileList = new javax.swing.JList();
        commandPanel = new javax.swing.JPanel();
        portComboBox = new javax.swing.JComboBox();
        portLabel = new javax.swing.JLabel();
        xStepsField = new javax.swing.JTextField();
        xStepsLabel = new javax.swing.JLabel();
        yStepsField = new javax.swing.JTextField();
        yStepsLabel = new javax.swing.JLabel();
        initializeButton = new javax.swing.JButton();
        sendAllButton = new javax.swing.JButton();
        sendNextButton = new javax.swing.JButton();
        disconectButton = new javax.swing.JButton();
        skipInitializationBox = new javax.swing.JCheckBox();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        openMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        jDialog1 = new javax.swing.JDialog();

        mainPanel.setName("mainPanel"); // NOI18N

        filePanel.setName(""); // NOI18N
        filePanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(panel.PlotterPanelApp.class).getContext().getResourceMap(PlotterPanelView.class);
        fileListLabel.setText(resourceMap.getString("fileListLabel.text")); // NOI18N
        fileListLabel.setName("fileListLabel"); // NOI18N
        filePanel.add(fileListLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));

        fileListPanel.setName("fileListPanel"); // NOI18N

        fileList.setName("fileList"); // NOI18N
        fileListPanel.setViewportView(fileList);

        filePanel.add(fileListPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 170, 240));

        commandPanel.setName(""); // NOI18N
        commandPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        portComboBox.setName("portComboBox"); // NOI18N
        commandPanel.add(portComboBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 220, -1));

        portLabel.setText(resourceMap.getString("portLabel.text")); // NOI18N
        portLabel.setName("portLabel"); // NOI18N
        commandPanel.add(portLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));

        xStepsField.setText(resourceMap.getString("xStepsField.text")); // NOI18N
        xStepsField.setName("xStepsField"); // NOI18N
        commandPanel.add(xStepsField, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 60, 110, -1));

        xStepsLabel.setText(resourceMap.getString("xStepsLabel.text")); // NOI18N
        xStepsLabel.setName("xStepsLabel"); // NOI18N
        commandPanel.add(xStepsLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, 110, 30));

        yStepsField.setText(resourceMap.getString("yStepsField.text")); // NOI18N
        yStepsField.setName("yStepsField"); // NOI18N
        commandPanel.add(yStepsField, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 90, 110, 30));

        yStepsLabel.setText(resourceMap.getString("yStepsLabel.text")); // NOI18N
        yStepsLabel.setName("yStepsLabel"); // NOI18N
        commandPanel.add(yStepsLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 110, 30));

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(panel.PlotterPanelApp.class).getContext().getActionMap(PlotterPanelView.class, this);
        initializeButton.setAction(actionMap.get("getInfoButton")); // NOI18N
        initializeButton.setText(resourceMap.getString("initializeButton.text")); // NOI18N
        initializeButton.setName("initializeButton"); // NOI18N
        commandPanel.add(initializeButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 190, 230, -1));

        sendAllButton.setAction(actionMap.get("sendAllCommands")); // NOI18N
        sendAllButton.setText(resourceMap.getString("sendAllButton.text")); // NOI18N
        sendAllButton.setName("sendAllButton"); // NOI18N
        commandPanel.add(sendAllButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 220, 230, -1));

        sendNextButton.setAction(actionMap.get("sendNextCommand")); // NOI18N
        sendNextButton.setText(resourceMap.getString("sendNextButton.text")); // NOI18N
        sendNextButton.setName("sendNextButton"); // NOI18N
        commandPanel.add(sendNextButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 250, 120, -1));

        disconectButton.setAction(actionMap.get("disconect")); // NOI18N
        disconectButton.setText(resourceMap.getString("disconectButton.text")); // NOI18N
        disconectButton.setName("disconectButton"); // NOI18N
        commandPanel.add(disconectButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 250, 110, -1));

        skipInitializationBox.setText(resourceMap.getString("skipInitializationBox.text")); // NOI18N
        skipInitializationBox.setName("skipInitializationBox"); // NOI18N
        commandPanel.add(skipInitializationBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 120, 150, -1));

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(filePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(commandPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(78, 78, 78))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(filePanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(commandPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(29, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        openMenuItem.setAction(actionMap.get("openFileMenu")); // NOI18N
        openMenuItem.setText(resourceMap.getString("openMenuItem.text")); // NOI18N
        openMenuItem.setName("openMenuItem"); // NOI18N
        fileMenu.add(openMenuItem);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 330, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                .addContainerGap(8, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        jDialog1.setName("jDialog1"); // NOI18N

        javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
        jDialog1.getContentPane().setLayout(jDialog1Layout);
        jDialog1Layout.setHorizontalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jDialog1Layout.setVerticalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel commandPanel;
    private javax.swing.JButton disconectButton;
    private javax.swing.JList fileList;
    private javax.swing.JLabel fileListLabel;
    private javax.swing.JScrollPane fileListPanel;
    private javax.swing.JPanel filePanel;
    private javax.swing.JButton initializeButton;
    private javax.swing.JDialog jDialog1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JComboBox portComboBox;
    private javax.swing.JLabel portLabel;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JButton sendAllButton;
    private javax.swing.JButton sendNextButton;
    private javax.swing.JCheckBox skipInitializationBox;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTextField xStepsField;
    private javax.swing.JLabel xStepsLabel;
    private javax.swing.JTextField yStepsField;
    private javax.swing.JLabel yStepsLabel;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;

}
